/**
 * Copyright 2010 upTick Pty Ltd
 *
 * Licensed under the terms of the GNU Lesser General Public License version 3 
 * as published by the Free Software Foundation. You may obtain a copy of the
 * License at: http://www.gnu.org/copyleft/lesser.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations 
 * under the License. 
 */

package au.com.uptick.serendipity.client.sales.presenter;

import au.com.uptick.serendipity.client.NameTokens;
import au.com.uptick.serendipity.client.presenter.MainPagePresenter;
import au.com.uptick.serendipity.client.sales.view.AccountsContextAreaListGrid;
import au.com.uptick.serendipity.client.sales.view.handlers.AccountsUiHandlers;
import au.com.uptick.serendipity.shared.action.RetrieveAccountsAction;
import au.com.uptick.serendipity.shared.action.RetrieveAccountsResult;
import au.com.uptick.serendipity.shared.dto.AccountsDto;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.Place;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

import java.util.List;

public class AccountsPresenter extends Presenter<AccountsPresenter.MyView, AccountsPresenter.MyProxy> implements AccountsUiHandlers {

    private final PlaceManager placeManager;
    private final DispatchAsync dispatcher;

    @ProxyCodeSplit
    @NameToken(NameTokens.accounts)
    public interface MyProxy extends Proxy<AccountsPresenter>, Place {
    }

    public interface MyView extends View, HasUiHandlers<AccountsUiHandlers> {
        AccountsContextAreaListGrid getListGrid();

        void setServerResponse(List<AccountsDto> accounts);
    }

    @Inject
    public AccountsPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, DispatchAsync dispatcher) {
        super(eventBus, view, proxy);

        getView().setUiHandlers(this);

        this.placeManager = placeManager;
        this.dispatcher = dispatcher;
    }

    @Override
    protected void onBind() {
        super.onBind();

        Log.debug("onBind()");

        // get the data for the View's ListGrid
        dispatcher.execute(new RetrieveAccountsAction(),
                           new AsyncCallback<RetrieveAccountsResult>() {
                               @Override
                               public void onFailure(Throwable caught) {
                                   Log.debug("onFailure() - " + caught.getMessage());
                               }

                               @Override
                               public void onSuccess(RetrieveAccountsResult result) {
                                   Log.debug("onSuccess()");
                                   getView().setServerResponse(result.getAccountDtos());
                               }
                           });
    }

    @Override
    protected void onReveal() {
        super.onReveal();

        Log.debug("onReveal() - " + NameTokens.accounts);

        MainPagePresenter.getNavigationPaneHeader().setContextAreaHeaderLabelContents(NameTokens.accounts);
        MainPagePresenter.getNavigationPane().selectRecord(NameTokens.accounts);
    }

    @Override
    protected void onReset() {
        super.onReset();

        Log.debug("onReset()");
    }

    @Override
    protected void revealInParent() {
        RevealContentEvent.fire(this, MainPagePresenter.TYPE_SetContextAreaContent,
                                this);
    }

    // as per AccountsRecord
    private static final String ACCOUNT_ID = "accountId";
    private static final String ACTIVITY = "activity";
    private static final String EDIT = "edit";

    public void onRecordDoubleClicked(String accountId) {

        // String url = getRelativeURL("Account.html");
        String url = getRelativeURL("Account.html?accountId=3&activity=edit&gwt.codesvr=127.0.0.1:9997");
        Window.open(url, "_blank", "width=760, height=480");

        Log.debug("Window.open() : " + url);


        /*

        if (accountId.length() != 0) {
          PlaceRequest placeRequest = new PlaceRequest(NameTokens.accountPage);
          placeRequest = placeRequest.with(ACTIVITY, EDIT).with(ACCOUNT_ID, accountId);
          placeManager.revealPlace(placeRequest);
        }

        */
    }

    public static final String LOCAL_HOST = "http://127.0.0.1:8888/";
    public static final String REMOTE_HOST = "http://crmdipity.com/";

    public static String getRelativeURL(String url) {
        String realModuleBase;

        if (GWT.isScript()) {
            String moduleBase = GWT.getModuleBaseURL();

            Log.debug("GWT.isScript() is true - ModuleBaseURL: " + moduleBase);

            // Use for deployment to PRODUCTION server
            realModuleBase = REMOTE_HOST;

            // Use to test compiled browser locally
            if (moduleBase.indexOf("localhost") != -1) {
                realModuleBase = LOCAL_HOST;
            }
        } else {
            Log.debug("GWT.isScript() is not true");

            // This is the URL for GWT Hosted mode
            realModuleBase = LOCAL_HOST;
        }

        return realModuleBase + url;
    }
}
